package com.stars.easyms.logger.support.logback.util;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.gaffer.GafferUtil;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.classic.util.ContextInitializer;
import ch.qos.logback.classic.util.EnvUtil;
import ch.qos.logback.core.LogbackException;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.status.ErrorStatus;
import ch.qos.logback.core.status.StatusManager;
import com.stars.easyms.logger.support.logback.joran.EasyMsJoranConfigurator;

import java.net.URL;

/**
 * <p>className: EasyMsLogbackContextInitializer</p>
 * <p>description: 自定义ContextInitializer类</p>
 *
 * @author guoguifang
 * @date 2019-08-20 10:21
 * @since 1.3.0
 */
public final class EasyMsLogbackContextInitializer extends ContextInitializer {

    private final LoggerContext easyMsLoggerContext;

    public EasyMsLogbackContextInitializer(LoggerContext loggerContext) {
        super(loggerContext);
        this.easyMsLoggerContext = loggerContext;
    }

    @Override
    public void configureByResource(URL url) throws JoranException {
        if (url == null) {
            throw new IllegalArgumentException("URL argument cannot be null");
        }
        final String urlString = url.toString();
        if (urlString.endsWith("groovy")) {
            if (EnvUtil.isGroovyAvailable()) {
                GafferUtil.runGafferConfiguratorOn(easyMsLoggerContext, this, url);
            } else {
                StatusManager sm = easyMsLoggerContext.getStatusManager();
                sm.add(new ErrorStatus("Groovy classes are not available on the class path. ABORTING INITIALIZATION.", easyMsLoggerContext));
            }
        } else if (urlString.endsWith("xml")) {
            JoranConfigurator configurator = new EasyMsJoranConfigurator();
            configurator.setContext(easyMsLoggerContext);
            configurator.doConfigure(url);
        } else {
            throw new LogbackException("Unexpected filename extension of file [" + url.toString() + "]. Should be either .groovy or .xml");
        }
    }

    /**
     * 由于父类方法设置了权限，因此为了覆盖父类的方法使用相同的方法名称
     */
    public void joranConfigureByResource(URL url) throws JoranException {
        JoranConfigurator configurator = new EasyMsJoranConfigurator();
        configurator.setContext(easyMsLoggerContext);
        configurator.doConfigure(url);
    }
}